#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <gmp.h>

#define ITER 100000000 //Numero de pontos aleatorio gerados

int main (int argc, char *argv[]) 
{
	//Variaveis do algoritmo
	mpf_t pi;
	mpf_t pointsIn;
	mpf_t pointsTotal;
	
	//Variaveis para calcular tempo de execucao
	clock_t t0, tf;
	
	//Variaveis para armazenar os pontos aleatorios
	double x, y;
	long i;
	
	//Abre o arquivo onde sera impresso o resultado final
	FILE *piFile = fopen("out_monteCarloSeq.txt","w+");

	if(piFile == NULL) 
	{
		return EXIT_FAILURE;
	}

	//Inicia o relogio
	printf("Starting...\n");
	t0 = clock();
	
	//Setar precisão (usar todas as 10 milhões de casas) e inicializar variaveis do metodo
	mpf_set_default_prec(40000000);
	srand(time(NULL));
	mpf_init(pointsIn);
	mpf_init(pointsTotal);
	mpf_init(pi);
	
	//Loop principal
	for (i = 0 ; i < ITER ; i++) 
	{
		x = (double)(RAND_MAX - rand())/(double)RAND_MAX;
		y = (double)(RAND_MAX - rand())/(double)RAND_MAX;

		if(x*x + y*y <= 1.0) 
		{
			mpf_add_ui(pointsIn, pointsIn, 1);
			mpf_add_ui(pointsTotal, pointsTotal, 1);
		}
		else
		{
			mpf_add_ui(pointsTotal, pointsTotal, 1);
		}
	}
	
	mpf_div(pi, pointsIn, pointsTotal); 
	mpf_mul_ui(pi,pi,4); // pi = 4*pontosDentro/pontosTotal 
	
	tf = clock();

	mpf_out_str(piFile,10,250000,pi);
	fprintf(piFile,"\n");

	printf("Time: %lf - Number of Points: %ld\n",(double)(tf - t0)/(double)CLOCKS_PER_SEC,i);

	fclose(piFile);

	return 0;
}
